<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import httpClient from '../utils/http'
import CodeEditor from '../components/CodeEditor.vue'

const route = useRoute()

// 定义接口详情的类型
interface MockDetail {
  id: string
  name: string
  url: string
  method: string
  headers: Record<string, any>
  body: Record<string, any>
  status_code: number
  response: string
  created_at: string
  updated_at: string
}

// Mock 接口详情数据 - 初始值
const initialMockDetail: MockDetail = {
  id: '',
  name: '',
  url: '',
  method: '',
  headers: {},
  body: {},
  status_code: 200,
  response: '{}',
  created_at: '',
  updated_at: ''
}

// 使用带类型的 ref
const mockDetail = ref<MockDetail>({...initialMockDetail})

// 用于显示的 JSON 字符串
const headersJson = ref('{}')
const bodyJson = ref('{}')

// 安全的 JSON 字符串化函数
const safeStringify = (data: any) => {
  try {
    return JSON.stringify(data || {}, null, 2)
  } catch (error) {
    console.error('JSON 序列化失败:', error)
    return '{}'
  }
}

// 获取状态码类别
const getStatusClass = (statusCode: number) => {
  if (statusCode >= 200 && statusCode < 300) return 'success'
  if (statusCode >= 300 && statusCode < 400) return 'redirect'
  if (statusCode >= 400 && statusCode < 500) return 'client-error'
  if (statusCode >= 500) return 'server-error'
  return ''
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取 Mock 接口详情
const fetchMockDetail = async () => {
  try {
    // 确保路由参数 id 存在
    if (!route.params.id) {
      console.error('缺少接口 ID 参数')
      return
    }
    
    const response = await httpClient.get(`/v1/mocs/${route.params.id}`)
    
    // 检查响应结构
    if (response?.data?.success && response.data.data) {
      // 合并数据，确保所有字段都被覆盖
      mockDetail.value = {
        ...initialMockDetail,
        ...response.data.data
      }
      
      // 处理嵌套对象，确保它们是对象类型
      const headers = typeof mockDetail.value.headers === 'object' 
        ? mockDetail.value.headers 
        : {}
      
      const body = typeof mockDetail.value.body === 'object' 
        ? mockDetail.value.body 
        : {}
      
      // 更新 JSON 字符串
      headersJson.value = safeStringify(headers)
      bodyJson.value = safeStringify(body)
      
      // 更新完整的响应数据
      mockDetail.value.response = safeStringify(response.data)
    } else {
      console.error('接口返回格式不正确:', response)
    }
  } catch (error) {
    console.error('获取接口详情失败:', error)
  }
}

onMounted(() => {
  fetchMockDetail()
})
</script>

<template>
  <div class="mock-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <h2>{{ mockDetail.name }}</h2>
        </div>
      </template>
      
      <div class="detail-grid">
        <div class="detail-item">
          <span class="detail-label">ID:</span>
          <span class="detail-value">{{ mockDetail.id }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">URL:</span>
          <span class="detail-value url-value">{{ mockDetail.url }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">方法:</span>
          <span class="detail-value method-value {{ mockDetail.method.toLowerCase() }}">{{ mockDetail.method }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">状态码:</span>
          <span class="detail-value status-value {{ getStatusClass(mockDetail.status_code) }}">{{ mockDetail.status_code }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">创建时间:</span>
          <span class="detail-value">{{ formatDate(mockDetail.created_at) }}</span>
        </div>
        
        <div class="detail-item">
          <span class="detail-label">更新时间:</span>
          <span class="detail-value">{{ formatDate(mockDetail.updated_at) }}</span>
        </div>
      </div>
      
      <div class="response-section">
        <h3>响应内容</h3>
        <div class="response-content">
          <CodeEditor :model-value="mockDetail.response" language="json" :read-only="true" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.mock-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.detail-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5em;
  color: #333;
  font-weight: 600;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-weight: 600;
  color: #666;
  margin-bottom: 5px;
  font-size: 0.9em;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.detail-value {
  font-size: 1em;
  color: #333;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #eee;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.url-value {
  font-family: 'Courier New', Courier, monospace;
  background-color: #f1f8ff;
  border-color: #c8e1ff;
  color: #0366d6;
}

.method-value {
  text-transform: uppercase;
  font-weight: bold;
  text-align: center;
}

.method-value.get {
  background-color: #f1f8ff;
  border-color: #c8e1ff;
  color: #0366d6;
}

.method-value.post {
  background-color: #f0fff4;
  border-color: #abf2c5;
  color: #28a745;
}

.method-value.put {
  background-color: #fff8e1;
  border-color: #ffe082;
  color: #ffc107;
}

.method-value.delete {
  background-color: #ffeef0;
  border-color: #fdb8c0;
  color: #dc3545;
}

.status-value {
  font-weight: bold;
  text-align: center;
}

.status-value.success {
  background-color: #f0fff4;
  border-color: #abf2c5;
  color: #28a745;
}

.status-value.redirect {
  background-color: #fff8e1;
  border-color: #ffe082;
  color: #ffc107;
}

.status-value.client-error {
  background-color: #ffeef0;
  border-color: #fdb8c0;
  color: #dc3545;
}

.status-value.server-error {
  background-color: #f8d7da;
  border-color: #f5c6cb;
  color: #721c24;
}

.response-section {
  padding: 0 20px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.response-section h3 {
  margin: 20px 0 15px;
  color: #333;
  font-weight: 600;
  align-self: flex-start;
}

.response-content {
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #eee;
  height: 500px;
  width: 100%;
  max-width: 800px;
  text-align: left;
}

/* Monaco Editor styles */
:deep(.monaco-editor) {
  border-radius: 4px;
}

@media (max-width: 768px) {
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .mock-detail {
    padding: 10px;
  }
  
  .card-header,
  .detail-grid,
  .response-section {
    padding: 15px;
  }
}
</style>